<template>
    <div class="section">
        <!-- 第一个筛选条件和图表 -->
        <div class="section1">
            <h1>年度Incident数量统计（原始数据）</h1>
            <div class="section2" >
                <label>年份：</label>
                <input v-model="year" type="number" placeholder="请输入年份" />

                <label>月份范围：</label>
                <select v-model="monthRange">
                    <option value="1-6">1-6月</option>
                    <option value="7-12">7-12月</option>
                </select>

                <label>项目：</label>
                <select v-model="project">
                    <option value="">请选择项目</option>
                    <option value="Shinny">Shinny</option>
                    <option value="Other">Other</option>
                </select>

                <button @click="fetchData">查询</button>
            </div>

            <!-- 第一个图表容器 -->
            <div ref="chart" class="chart-container"></div>
        </div>

        <!-- 第二个筛选条件和图表 -->
        <div class="section1">
            <h1>月度Incident优先级统计（原始数据）</h1>
            <div class="section2">
                <label>年份：</label>
                <input v-model="year2" type="number" placeholder="请输入年份" />

                <label>月份：</label>
                <select v-model="selectedMonth2">
                    <option value="">请选择月份</option>
                    <option v-for="month in months" :key="month" :value="month">{{ month }}月</option>
                </select>

                <label>项目：</label>
                <select v-model="project2">
                    <option value="">请选择项目</option>
                    <option value="Shinny">Shinny</option>
                    <option value="Other">Other</option>
                </select>

                <button @click="fetchData2">查询</button>
            </div>

            <!-- 第二个图表容器 -->
            <div ref="chart2" class="chart-container"></div>
        </div>

        <!-- 第三个筛选条件和图表 -->
        <div class="section1">
            <h1>周度Incident统计（原始数据）</h1>
            <div class="section2">
                <label>年份：</label>
                <input v-model="year3" type="number" placeholder="请输入年份" />

                <label>周数：</label>
                <select v-model="selectedWeek">
                    <option value="">请选择周</option>
                    <option v-for="week in weeks" :key="week" :value="week">第{{ week }}周</option>
                </select>

                <label>项目：</label>
                <select v-model="project3">
                    <option value="">请选择项目</option>
                    <option value="Shinny">Shinny</option>
                    <option value="Other">Other</option>
                </select>
                <label>组别：</label>
                <select v-model="assignmentGroup">
                    <option value="">请选择组</option>
                    <option value="Cloud-Administrators-L1">Cloud-Administrators-L1</option>
                    <option value="Cloud-Administrators-L2">Cloud-Administrators-L2</option>
                </select>

                <button @click="fetchData3">查询</button>
            </div>

            <!-- 第三个图表容器 -->
            <div ref="chart3" class="chart-container"></div>
            <div ref="chart4" class="chart-container"></div>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts';

export default {
    data() {
        return {
            year: new Date().getFullYear(), // 默认当前年份
            monthRange: '1-6', // 默认1-6月
            project: '', // 项目名称
            year2: new Date().getFullYear(), // 第二个筛选条件的年份
            selectedMonth2: '', // 第二个筛选条件的月份
            project2: '', // 第二个筛选条件的项目名称
            months: Array.from({ length: 12 }, (_, i) => i + 1), // 生成1到12的月份数组
            year3: new Date().getFullYear(), // 第三个筛选条件的年份
            selectedWeek: '', // 第三个筛选条件的周数
            project3: '', // 第三个筛选条件的项目名称
            assignmentGroup: '', // Assignment Group 参数
            weeks: Array.from({ length: 53 }, (_, i) => i + 1), // 生成1到53的周数组
            chart: null, // ECharts实例
            chart2: null, // 第二个ECharts实例
            chart3: null, // 第三个ECharts实例
            chart4: null, // 第四个ECharts实例
        };
    },
    mounted() {
        this.initChart();
        this.initChart2();
        this.initChart3();
        this.initChart4(); //
        this.fetchData();
    },
    methods: {
        initChart() {
            this.chart = echarts.init(this.$refs.chart);
        },
        initChart2() {
            this.chart2 = echarts.init(this.$refs.chart2);
        },
        initChart3() {
            this.chart3 = echarts.init(this.$refs.chart3);
        },
         initChart4() { // 第四个图表暂时留空
             this.chart4 = echarts.init(this.$refs.chart4);
         },
        async fetchData() {
            try {
                console.log('请求参数:', {
                    year: this.year,
                    monthRange: this.monthRange,
                    project: this.project,
                });

                const response = await axios.get('http://localhost:3000/api/incidents_stats', {
                    params: {
                        year: this.year,
                        monthRange: this.monthRange,
                        project: this.project,
                    },
                });

                if (response.status !== 200) {
                    console.error('请求失败，状态码:', response.status);
                    alert('请求失败，请检查控制台日志。');
                    return;
                }

                const data = response.data.data;
                if (!data || data.length === 0) {
                    console.warn('没有返回数据');
                    alert('没有返回数据');
                    return;
                }

                this.renderChart(data);
            } catch (error) {
                console.error('获取数据失败:', error);
                alert('获取数据失败，请检查控制台日志！');
            }
        },
        async fetchData2() {
            try {
                console.log('第二个请求参数:', {
                    year: this.year2,
                    month: this.selectedMonth2,
                    project: this.project2,
                });

                const response = await axios.get('http://localhost:3000/api/incidents_stats/monthly/priority', {
                    params: {
                        year: this.year2,
                        month: this.selectedMonth2,
                        project: this.project2,
                    },
                });

                if (response.status !== 200) {
                    console.error('请求失败，状态码:', response.status);
                    alert('请求失败，请检查控制台日志。');
                    return;
                }

                const data = response.data.data;
                if (!data || data.length === 0) {
                    console.warn('没有返回数据');
                    alert('没有返回数据');
                    return;
                }

                this.renderChart2(data);
            } catch (error) {
                console.error('获取第二个数据失败:', error);
                alert('获取第二个数据失败，请检查控制台日志！');
            }
        },
        async fetchData3() {
            try {
                console.log('第三个请求参数:', {
                    year: this.year3,
                    week: this.selectedWeek,
                    project: this.project3,
                    assignmentGroup: this.assignmentGroup,
                });

                const response = await axios.get('http://localhost:3000/api/incidents_stats/weekly', {
                    params: {
                        year: this.year3,
                        week: this.selectedWeek,
                        project: this.project3,
                        assignmentGroup: this.assignmentGroup,
                    },
                });

                if (response.status !== 200) {
                    console.error('请求失败，状态码:', response.status);
                    alert('请求失败，请检查控制台日志。');
                    return;
                }

                const data = response.data;
                console.log('后端返回的数据:', data); // 打印返回的数据
                if (!data || !data.chart1 || !data.chart2) {
                    console.warn('没有返回数据');
                    alert('没有返回数据');
                    return;
                }

                this.renderChart3(data.chart1);
                this.renderChart4(data.chart2);
            } catch (error) {
                console.error('获取第三个数据失败:', error);
                alert('获取第三个数据失败，请检查控制台日志！');
            }
        },
        renderChart(data) {
            const months = data.map((item) => `${item.month}月`);
            const total = data.map((item) => item.total);
            const closedResolved = data.map((item) => item.closedResolved);
            const inProgress = data.map((item) => item.inProgress);

            const option = {
                title: {
                    text: '年度Incident数量统计（原始数据）',
                    left: 'left',
                    top: '10px',
                    textStyle: {
                        fontSize: 18,
                        fontWeight: 'bold',
                        color: '#333',
                    },
                },
                tooltip: {
                    trigger: 'axis',
                },
                legend: {
                    data: ['总数量', 'Closed/Resolved', 'Work In Progress/Open/Awaiting User Info'],
                    bottom: '30px',
                    textStyle: {
                        fontSize: 14,
                        color: '#333',
                    },
                },
                xAxis: {
                    type: 'category',
                    data: months,
                    axisLine: {
                        lineStyle: {
                            color: '#333',
                        },
                    },
                },
                yAxis: {
                    type: 'value',
                    axisLine: {
                        lineStyle: {
                            color: '#333',
                        },
                    },
                },
                series: [
                    {
                        name: '总数量',
                        type: 'bar',
                        data: total,
                        itemStyle: {
                            color: '#4CAF50',
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}',
                        },
                    },
                    {
                        name: 'Closed/Resolved',
                        type: 'bar',
                        data: closedResolved,
                        itemStyle: {
                            color: '#2196F3',
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}',
                        },
                    },
                    {
                        name: 'Work In Progress/Open/Awaiting User Info',
                        type: 'bar',
                        data: inProgress,
                        itemStyle: {
                            color: '#FF9800',
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}',
                        },
                    },
                ],
                backgroundColor: '#f9f9f9',
                grid: {
                    top: '60px',
                    bottom: '90px',
                    left: '40px',
                    right: '40px',
                },
            };

            this.chart.setOption(option);
        },
        renderChart2(data) {
            const priorities = ['1 - Critical', '2 - High', '3 - Moderate', '4 - Low'];
            const total = [];
            const closedResolved = [];
            const inProgress = [];

            priorities.forEach((priority) => {
                const priorityData = data[0]?.priorities[priority];
                total.push(priorityData ? priorityData.total : 0);
                closedResolved.push(priorityData ? priorityData.closedResolved : 0);
                inProgress.push(priorityData ? priorityData.inProgress : 0);
            });

            const option = {
                title: {
                    text: '月度Incident优先级统计（原始数据）',
                    left: 'left',
                    top: '10px',
                    textStyle: {
                        fontSize: 18,
                        fontWeight: 'bold',
                        color: '#333',
                    },
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow',
                    },
                },
                legend: {
                    data: ['总数量', 'Closed/Resolved', 'Work In Progress/Open/Awaiting User Info'],
                    bottom: '30px',
                    textStyle: {
                        fontSize: 14,
                        color: '#333',
                    },
                },
                xAxis: {
                    type: 'category',
                    data: priorities,
                    axisLine: {
                        lineStyle: {
                            color: '#333',
                        },
                    },
                },
                yAxis: {
                    type: 'value',
                    axisLine: {
                        lineStyle: {
                            color: '#333',
                        },
                    },
                },
                series: [
                    {
                        name: '总数量',
                        type: 'bar',
                        data: total,
                        itemStyle: {
                            color: '#4CAF50',
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}',
                        },
                    },
                    {
                        name: 'Closed/Resolved',
                        type: 'bar',
                        data: closedResolved,
                        itemStyle: {
                            color: '#2196F3',
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}',
                        },
                    },
                    {
                        name: 'Work In Progress/Open/Awaiting User Info',
                        type: 'bar',
                        data: inProgress,
                        itemStyle: {
                            color: '#FF9800',
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}',
                        },
                    },
                ],
                backgroundColor: '#f9f9f9',
                grid: {
                    top: '60px',
                    bottom: '90px',
                    left: '40px',
                    right: '40px',
                },
            };

            this.chart2.setOption(option);
        },
        renderChart3(data) {
        // 提取优先级列表
        const priorities = ['1 - Critical', '2 - High', '3 - Moderate', '4 - Low'];

        // 初始化数据数组
        const total = [];
        const closedResolved = [];
        const inProgress = [];

        // 遍历优先级，提取每个优先级的数据
        priorities.forEach((priority) => {
            const priorityData = data[0]?.priorities[priority];
            total.push(priorityData ? priorityData.total : 0);
            closedResolved.push(priorityData ? priorityData.closedResolved : 0);
            inProgress.push(priorityData ? priorityData.inProgress : 0);
        });

        // 构建 ECharts 配置
        const option = {
            title: {
                text: '周度Incident优先级统计（原始数据）',
                left: 'left',
                top: '10px',
                textStyle: {
                    fontSize: 18,
                    fontWeight: 'bold',
                    color: '#333',
                },
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow',
                },
            },
            legend: {
                data: ['总数量', 'Closed/Resolved', 'Work In Progress/Open/Awaiting User Info'],
                bottom: '30px',
                textStyle: {
                    fontSize: 14,
                    color: '#333',
                },
            },
            xAxis: {
                type: 'category',
                data: priorities,
                axisLine: {
                    lineStyle: {
                        color: '#333',
                    },
                },
            },
            yAxis: {
                type: 'value',
                axisLine: {
                    lineStyle: {
                        color: '#333',
                    },
                },
            },
            series: [
                {
                    name: '总数量',
                    type: 'bar',
                    data: total,
                    itemStyle: {
                        color: '#4CAF50',
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}',
                    },
                },
                {
                    name: 'Closed/Resolved',
                    type: 'bar',
                    data: closedResolved,
                    itemStyle: {
                        color: '#2196F3',
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}',
                    },
                },
                {
                    name: 'Work In Progress/Open/Awaiting User Info',
                    type: 'bar',
                    data: inProgress,
                    itemStyle: {
                        color: '#FF9800',
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}',
                    },
                },
            ],
            backgroundColor: '#f9f9f9',
            grid: {
                top: '60px',
                bottom: '90px',
                left: '40px',
                right: '40px',
            },
        };

        // 设置 ECharts 配置
        this.chart3.setOption(option);
        },
        renderChart4(data) {
        const incidentTypes = ['监控工具发现', '用户报告'];
        const total = [];
        const closedResolved = [];
        const inProgress = [];

        incidentTypes.forEach((incidentType) => {
            const typeData = data[0]?.incidentTypes[incidentType];
            total.push(typeData ? typeData.total : 0);
            closedResolved.push(typeData ? typeData.closedResolved : 0);
            inProgress.push(typeData ? typeData.inProgress : 0);
        });

        const option = {
            title: {
                text: '周度Incident类型统计（监控工具 vs 用户报告）',
                left: 'left',
                top: '10px',
                textStyle: {
                    fontSize: 18,
                    fontWeight: 'bold',
                    color: '#333',
                },
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow',
                },
            },
            legend: {
                data: ['总数量', 'Closed/Resolved', 'Work In Progress/Open/Awaiting User Info'],
                bottom: '30px',
                textStyle: {
                    fontSize: 14,
                    color: '#333',
                },
            },
            xAxis: {
                type: 'category',
                data: incidentTypes,
                axisLine: {
                    lineStyle: {
                        color: '#333',
                    },
                },
            },
            yAxis: {
                type: 'value',
                axisLine: {
                    lineStyle: {
                        color: '#333',
                    },
                },
            },
            series: [
                {
                    name: '总数量',
                    type: 'bar',
                    data: total,
                    itemStyle: {
                        color: '#4CAF50',
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}',
                    },
                },
                {
                    name: 'Closed/Resolved',
                    type: 'bar',
                    data: closedResolved,
                    itemStyle: {
                        color: '#2196F3',
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}',
                    },
                },
                {
                    name: 'Work In Progress/Open/Awaiting User Info',
                    type: 'bar',
                    data: inProgress,
                    itemStyle: {
                        color: '#FF9800',
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}',
                    },
                },
            ],
            backgroundColor: '#f9f9f9',
            grid: {
                top: '60px',
                bottom: '90px',
                left: '40px',
                right: '40px',
            },
        };

        this.chart4.setOption(option);
        },
      
        
    },
};
</script>

<style scoped>

.section {
    position: relative;
    top: 0px;
    overflow-y: auto; /* 启用垂直滚动条 */
    /*text-align: center；*/
}

.section1 {
    font-size: 15px;
    margin-top: 20px;
    margin-bottom: 20px; /* 为每个部分添加底部间距 */
    background-color: white; /* 白色背景 */
    border-radius: 10px; /* 圆角 */
    padding: 20px; /* 内边距 */
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 添加阴影 */
    text-align: center；
    
}
.section2 {
    text-align: center；
}

.chart-container {
    width: 100%; /* 设置宽度为100% */
    height: 500px; /* 设置高度为500px */
    padding: 20px; /* 添加内边距以增加空间 */
    box-sizing: border-box; /* 确保内边距不会影响总宽度 */
}

/* 添加一些基本样式以美化界面 */
div {
    margin: 20px;
}

label {
    margin-right: 10px;
}

input[type="number"],
select {
    margin-right: 20px;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 4px;
}

button {
    padding: 5px 10px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button:hover {
    background-color: #0056b3;
}
</style>